#!/bin/env bash

set -e

#项目根目录
CURRENT_PATH=$(dirname "$(readlink -f "$0")")
ROOT_PATH=$(dirname $CURRENT_PATH)

SERVER=${2}
SERVER_PORT=${3}
SERVICE_FILE=${CURRENT_PATH}/service/hobyadm.service

ServiceName=${1}
ServiceFileName=${ServiceName}.service


if [[ "${SERVER}" == "" ]] || [[ "${SERVER_PORT}" == "" ]] || [[ "${ServiceName}" == "" ]]; then
  echo "请输入要发布的服务器或者服务名称"
  exit 1
fi


function confirm_with_default()
{
    local default="$2"
    local prompt="${1} [Y/n] "

    if [[ "$default" =~ ^[Yy]$ ]]; then
        prompt="${1} [Y/n] "
    else
        prompt="${1} [y/N] "
    fi

    read -r -p "$prompt" answer

    # 如果用户直接按回车，使用默认值
    if [[ -z "$answer" ]]; then
        answer="$default"
    fi

    [[ "$answer" =~ ^[Yy]$ ]] && return 0 || return 1
}


conform="确认将服务【${ServiceName}】将发布至服务器【${SERVER}:${SERVER_PORT}】"

if confirm_with_default $conform "Y"; then
    echo "确认发布！"
else
   echo "取消发布！"
   exit 1
fi

MAIN=${ROOT_PATH}/${ServiceName}
MAIN_SERVICE_FILE=${ROOT_PATH}/${ServiceFileName}

SERVER_ROOT_PATH=/var/www/${ServiceName}


function createServiceFile()
{
  cp ${SERVICE_FILE} ${MAIN_SERVICE_FILE}
  if [ "$(uname)" = "Darwin" ]; then
    sed -i "" "s:{{name}}:${ServiceName}:g;s:{{root}}:${SERVER_ROOT_PATH}:g" ${MAIN_SERVICE_FILE}
  else
    sed -i "s:{{name}}:${ServiceName}:g;s:{{root}}:${SERVER_ROOT_PATH}:g" ${MAIN_SERVICE_FILE}
  fi
  return 0
}


createServiceFile

#上传
scp -P ${SERVER_PORT} ${MAIN} ${SERVER}:/tmp
scp -P ${SERVER_PORT} ${MAIN_SERVICE_FILE} ${SERVER}:/tmp

# 复制重启
cmd="sudo mkdir -p ${SERVER_ROOT_PATH}"
cmd="$cmd && sudo mv -f /tmp/${ServiceName} ${SERVER_ROOT_PATH}/${ServiceName}"
cmd="$cmd && sudo mv -f /tmp/${ServiceFileName} ${SERVER_ROOT_PATH}/${ServiceFileName}"
cmd="$cmd && sudo [ -L /etc/systemd/system/${ServiceFileName} ] || sudo  ln -s ${SERVER_ROOT_PATH}/${ServiceFileName} /etc/systemd/system/${ServiceFileName}"
cmd="$cmd && sudo chmod +x ${SERVER_ROOT_PATH}/${ServiceName}"
cmd="$cmd && sudo systemctl daemon-reload"
cmd="$cmd && sudo systemctl restart ${ServiceName}.service"
cmd="$cmd && sudo systemctl status ${ServiceName}"

echo $cmd

ssh -p ${SERVER_PORT} ${SERVER} "${cmd}"

